package com.oly.cms.hand.security.hand;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSONObject;
import com.grace.common.core.domain.AjaxResult;
import com.grace.common.utils.ServletUtils;
import com.oly.cms.general.service.taglib.ConfigTag;

/**
 * 登录失败自定义处理类
 * 
 * @author 止戈
 */
@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Autowired
    private ConfigTag configTag;

    /**
     * 认证失败处理方法。
     * 当用户认证失败时，此方法将被调用，用于处理相应的逻辑。
     * 
     * @param request   HttpServletRequest对象，代表客户端的HTTP请求
     * @param response  HttpServletResponse对象，用于向客户端发送响应
     * @param exception AuthenticationException对象，封装了认证失败的异常信息
     * @throws IOException      如果在处理过程中发生IO错误
     * @throws ServletException 如果在处理过程中发生Servlet相关异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {

        if (ServletUtils.isAjaxRequest(request)) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.error(exception.getMessage())));
            response.getWriter().flush();
        } else {
            response.sendRedirect(ThemeUtils.getDomain(request, configTag) + "/login?error=true&msg="
                    + URLEncoder.encode(exception.getMessage(), "UTF-8"));
        }

    }
}